create table student(
id varchar2(10) primary key,
name varchar2(20) not null,
addr varchar2(40) not null,
detail varchar2(100)
);
id 학생 아이디
name 학생 이 름
addr 학생 주 소
detail 학생 소 개
--------------------------------------
2) 학생 DTO --> DTO는 직렬화한 객체로 DB의 한 row를
저장하는 역할한다. get/set을 메서드로 갖는다.
package kr.hk;
import java.io.Serializable;
public class StudentDTO implements Serializable {
private String id; //id 학생 아이디
private String name; //name 학생 이 름
private String addr; //addr 학생 주 소
private String detail; //detail 학생 소 개
public StudentDTO( String id, String name,
String addr, String detail) {
this.setId(id); //this.id=id;
this.setName(name);
this.setAddr(addr);
this.setDetail(detail);
}
public StudentDTO() {
}
/**
* @return Returns the addr.
*/
public String getAddr() {
return addr;
}
/**
* @param addr The addr to set.
*/
public void setAddr(String addr) {
this.addr = addr;
}
/**
* @return Returns the detail.
*/
public String getDetail() {
return detail;
}
/**
* @param detail The detail to set.
*/
public void setDetail(String detail) {
this.detail = detail;
}
/**
* @return Returns the id.
*/
public String getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(String id) {
this.id = id;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
public String toString(){
StringBuffer sb=new StringBuffer();
sb.append("["+id+", ")
.append(name+", ")
.append(addr+", ")
.append(this.detail+"]");
return sb.toString();
}
}//class
-----------------------------------
3) 예외
학생을 정보를 입력하려고 할때 이미 그 정보가 존재할 경우
--> StudentIdDuplicateException
package kr.hk;
public class StudentIdDuplicateException extends Exception {
public StudentIdDuplicateException() {
super("이미 학생이 존재합니다.");
}
public StudentIdDuplicateException(String message) {
super(message);
}
}
----------------------------------
학생의 정보를 update, delete하려고 할 때 그 정보가 존재하지 않을 경우
--> StudentIdNotFoundException
package kr.hk;
public class StudentIdNotFoundException extends Exception {
public StudentIdNotFoundException() {
super("이런 학생은 존재하지 않습니다.");
}
public StudentIdNotFoundException(String message) {
super(message);
}
}
-----------------------------------
4) 드라이버, 연결, 쿼리 유틸클래스
package kr.hk;
public class StudentUtil {
public static final String DRIVER=
"oracle.jdbc.driver.OracleDriver";
public static final String url=
"jdbc:oracle:thin:@id:1521:sid";
public static final String user="yyyy";
public static final String pass="xxxx";
public static final String INSERTSTUDENT=
"INSERT INTO STUDENT VALUES(?,?,?,?)";
public static final String SELECTSTUDENT=
"SELECT ID FROM STUDENT WHERE ID=?";
public static final String GETSTUDENT=
"SELECT * FROM STUDENT WHERE ID=?";
public static final String ALLSTUDENTS=
"SELECT * FROM STUDENT";
}
--------------------------------------------------------
5) DAO
package kr.hk;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
public class StudentDAO {
public StudentDAO() {
init(); //드라이버를 자동 로딩한다.
}
public void init(){
try {
Class.forName(StudentUtil.DRIVER);
System.out.println("1/6 드라이버 로딩 성공");
} catch (ClassNotFoundException e) {
System.out.println("1/6 드라이버 로딩 실패");
}
}//init
//getConnection()을 호출하면 자동 연결된다.
public Connection getConnection() throws SQLException{
Connection conn=null;
conn=DriverManager.getConnection(
StudentUtil.url,StudentUtil.user,StudentUtil.pass);
return conn;
}//getConnection
//close()를 호출하면 자동으로 해제된다.
public void close(Connection conn,
Statement stmt,
ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
}
}
if(conn!=null){
try {
conn.close();
System.out.println("6/6 close 성공");
} catch (SQLException e) {
System.out.println("6/6 close 실패");
}
}
}//close
//학생의 정보를 DB에 입력한다.
public void insertStudent(String id,
String name,String addr,
String detail) throws StudentIdDuplicateException{
if(hasStudent(id)){
throw new StudentIdDuplicateException(id+"가 이미 존배합니다.");
}
Connection conn=null;
PreparedStatement psmt=null;
try {
conn=this.getConnection();
psmt=conn.prepareStatement(StudentUtil.INSERTSTUDENT);
psmt.setString(1,id.trim());
psmt.setString(2,name.trim());
psmt.setString(3,addr.trim());
psmt.setString(4,detail.trim());
psmt.executeUpdate();
} catch (SQLException e) {
System.out.println("쿼리 실패 ");
}finally{
this.close(conn, psmt,null);
}
}
//id를 갖는 학생이 존재하는가 확인한다.
public boolean hasStudent(String id){
boolean hasS=false;
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
try {
conn=this.getConnection();
psmt=
conn.prepareStatement(StudentUtil.SELECTSTUDENT);
psmt.setString(1,id.trim());
rs=psmt.executeQuery();
if(rs.next()){
hasS=true;
}
} catch (SQLException e) {
System.out.println("연결 실패");
}finally{
this.close(conn, psmt,rs);
}
return hasS;
}//
//id를 갖는 학생의 정보를 DTO에 담아 리턴한다.
public StudentDTO getStudent(String id){
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
StudentDTO dto=new StudentDTO();
try {
conn=this.getConnection();
psmt=
conn.prepareStatement(StudentUtil.GETSTUDENT);
psmt.setString(1,id.trim());
rs=psmt.executeQuery();
while(rs.next()){
String sid=rs.getString(1);
String sname=rs.getString(2);
String saddr=rs.getString(3);
String sdetail=rs.getString(4);
dto.setId(sid);
dto.setName(sname);
dto.setAddr(saddr);
dto.setDetail(sdetail);
}
} catch (SQLException e) {
System.out.println("getStudent 실패");
}finally{
this.close(conn, psmt,rs);
}
return dto;
}//
//모든 학생을 Vector에 담아서 리턴한다.
//Vector에는 DTO 단위로 add된다.
public Vector getAllStudents(){
Connection conn=null;
PreparedStatement psmt=null;
ResultSet rs=null;
Vector v=new Vector(5,5);
try {
conn=this.getConnection();
psmt=
conn.prepareStatement(StudentUtil.ALLSTUDENTS);
rs=psmt.executeQuery();
while(rs.next()){
String sid=rs.getString(1);
String sname=rs.getString(2);
String saddr=rs.getString(3);
String sdetail=rs.getString(4);
StudentDTO dto=new StudentDTO();
dto.setId(sid);
dto.setName(sname);
dto.setAddr(saddr);
dto.setDetail(sdetail);
v.add(dto);
}
} catch (SQLException e) {
System.out.println("getStudent 실패");
}finally{
this.close(conn, psmt,rs);
}
return v;
}
//id를 갖는 학생이 있다면
//DB에서 제거하고
//없다면 없다 예외를 발생
public void deleteStudent(String id) throws StudentIdNotFoundException{
if(!hasStudent(id)){
throw new StudentIdNotFoundException(id+"가 존재하지 않습니다.");
}
Connection conn=null;
PreparedStatement psmt=null;
try {
conn=this.getConnection();
psmt=conn.prepareStatement(StudentUtil.DELESTUDENT);
psmt.setString(1,id.trim());
psmt.executeUpdate();
} catch (SQLException e) {
System.out.println("쿼리 실패 ");
}finally{
this.close(conn, psmt,null);
}
}
//update
//id를 갖는 학생이 있다면
//그 학생의 정보를 수정하고
//없다면 없다 예외를 발생
public void updateStudent(String id,
String name,String addr,
String detail) throws StudentIdNotFoundException {
if(!hasStudent(id)){
throw new StudentIdNotFoundException(id+"가 존재하지 않습니다.");
}
Connection conn=null;
PreparedStatement psmt=null;
try {
conn=this.getConnection();
psmt=conn.prepareStatement(StudentUtil.UPDASTUDENT);
int i=1;
psmt.setString(i++,name.trim());
psmt.setString(i++,addr.trim());
psmt.setString(i++,detail.trim());
psmt.setString(i++,id.trim());
psmt.executeUpdate();
} catch (SQLException e) {
System.out.println("쿼리 실패 ");
}finally{
this.close(conn, psmt,null);
}
}
}//class
--------------------------
6) 메인 -테스트
package kr.hk;
import java.util.Vector;
public class TestDto {
public static void main(String[] args) {
StudentDAO dao=new StudentDAO();
try {
dao.insertStudent("s005","홍길동","인천","반항심 많고.. ");
System.out.println("성공");
} catch (StudentIdDuplicateException e) {
System.out.println("insert 실패"+e);
}
StudentDTO sdt=dao.getStudent("s005");
System.out.println(sdt);
Vector v=dao.getAllStudents();
for(int i=0;i<v.size();i++){
StudentDTO ssdo=(StudentDTO)v.get(i);
System.out.println(ssdo);
}
}
}
[출처] [본문스크랩] 간단한 DAO 만들기 |작성자 어린양이
http://blog.naver.com/dlckdeo81?Redirect=Log&logNo=41775934 |